<?php

namespace App\Http\Controllers\Network;

use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\GoodsOrderModel;
use App\Models\yb\GoodsTypeModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\NetworkGoodsOrderModel;
use App\Models\yb\NetworkGoodsOrderDetailModel;
use App\Models\yb\NetworkCreditRecordModel;
use Illuminate\Http\Request;

class CreditController extends Controller
{

    /**
     * Get a JWT via given credentials.
     *  商品信用详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function GoodsDetail(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $goods_id = $request->post('goods_id');

        $take = $request->post('take', 10);
        
        $page = $request->post('page', 1);

        $credit_data = NetworkCreditRecordModel::where(['network_id'=>$user_data['id'],'goods_id'=>$goods_id])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$credit_data]);

    }
    
    
     /**
     * Get a JWT via given credentials.
     *  商品信用统计
     * @return \Illuminate\Http\JsonResponse
     */
    public function Statistics(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $goods_id = $request->post('goods_id');
        
        $goods_data = GoodsModel::where(['id'=>$goods_id])->select(['id','goods_title','goods_specs'])->first();

        $network_goods = NetworkGoodsModel::where(['goods_id'=>$goods_id,'network_id'=>$user_data['id']])->first();
        
        $statistics['cumulative_loading'] =  $network_goods['goods_stock']+$network_goods['goods_sales'];
        $statistics['cumulative_distribution'] =  $network_goods['goods_sales'];
        $statistics['cumulative_deduction'] =  NetworkGoodsOrderDetailModel::where(['network_id'=>$user_data['id'],'goods_id'=>$goods_id])->sum('credit_deduction');
        $statistics['credit_available'] =  $network_goods['return_credit'];
        
        $data['goods_data'] = $goods_data;
        $data['statistics'] = $statistics;


        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }




}
